package com.yenlien.traceyun.business.controller;


import com.yenlien.traceyun.business.entity.Check;
import com.yenlien.traceyun.business.interceptor.UserAuthUtil;
import com.yenlien.traceyun.business.service.CheckService;
import com.yenlien.traceyun.webase.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by LiuSha on 2020/6/11.
 */
@RestController
@RequestMapping("/check")
public class CheckController extends BaseController {
    @Autowired
    private CheckService checkService;

    @RequestMapping(value = "/findByList", method = RequestMethod.POST)
    public Object findByList(@RequestBody Check check) {
        check.setCompanyId(UserAuthUtil.getLoginUser().getCompanyId());
        return buildPage(checkService.findByList(check));
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public Object save(Check check, HttpServletRequest request) throws Exception {
        List<MultipartFile> files = new ArrayList<>();
        if (!StringUtils.isEmpty(((MultipartHttpServletRequest) request).getFile("files"))) {
            files = ((MultipartHttpServletRequest) request).getFiles("files");
        }
        check.setCompanyId(UserAuthUtil.getLoginUser().getCompanyId());
        checkService.save(check, files);
        return success("success");
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Object update(Check check, HttpServletRequest request) throws Exception {
        List<MultipartFile> files = new ArrayList<>();
        if (!StringUtils.isEmpty(((MultipartHttpServletRequest) request).getFile("files"))) {
            files = ((MultipartHttpServletRequest) request).getFiles("files");
        }
        checkService.update(check, files);
        return success("success");
    }

    @RequestMapping(value = "/findById/{id}", method = RequestMethod.GET)
    public Object findById(@PathVariable String id) {
        return success(checkService.findById(id));
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public Object delete(@PathVariable String id) {
        checkService.delete(id);
        return success("success");
    }

    @RequestMapping(value = "/findByAll", method = RequestMethod.GET)
    public Object findByAll() {
        return success(checkService.findAll(UserAuthUtil.getLoginUser().getCompanyId()));
    }

}
